// 论坛帖子模块
const router =  require('express').Router()
const query = require('../mysql/index');
const timeFormat = require('../utils/timeFormat');


// 读取文章类型
router.get("/getType",async(req,res)=>{
    let data = await query("select * from type");
    res.json({
        code:0,
        data
    })
})

/**
 * 数组数据分类
 * @param {*} arr 
 * @param {*} type 
 * @param {*} value 
 */
function sort(data){

    function search(arr,type,value){
        let res = false;
        arr.forEach((item,index)=>{
            if(item[type] == value){
                res = {index};
            }
        })
        return res;
    }

    let obj = [];
    
    data.forEach((item)=>{
        let isExistence = search(obj,'type',item.type_id);
        if(isExistence){
            obj[isExistence.index].data.push(item)
        }else{
            obj.push({
                type:item.type_id,
                typeName:item.type_name,
                data:[item]
            })
        }
    })

    return obj;
    
}

router.get("/articleList",async(req,res)=>{
    // 查询每个分类下的前5条数据
    let sql = `
    SELECT 
    a.*,(SELECT name from type where id = a.type_id) as type_name
FROM
    article AS a,
    (SELECT 
        GROUP_CONCAT(id order by id desc) AS ids
    FROM
        article
    GROUP BY type_id) AS b
WHERE
    FIND_IN_SET(a.id, b.ids) BETWEEN 1 AND 3
ORDER BY a.type_id ASC, a.id DESC;
    `
    let data = await query(sql)
    res.json({
        code:0,
        data:sort(data)
    })
})

router.get("/list/:typeId",async(req,res)=>{
    let type =  await query("select * from type where id = " + req.params.typeId);
    let sql = "select * from article where type_id = ?";
    let data = await query(sql,[req.params.typeId]);
    res.render("articles",{data,title:type[0].name})
})

router.get("/search/:key",async(req,res)=>{
    let sql = "select * from article where title like '%" + req.params.key + "%'";
    let data = await query(sql);
    res.render("articles",{data,title:`关于“${req.params.key}”的搜索结果：`})
})


// 删除某个类型，删除之前必须把该类型下所有文章都删除掉
router.post("/delType/:id",async(req,res)=>{
    // 查询该类型下是否有文章
    let articles = await query("select id from article where type_id=?",[req.params.id])
    // 如果有文章，则不允许删除该分类
    if(articles.length){
        res.json({
            code:401,
            msg:'该分类下有文章，不允许删除'
        })
    }else{
        // 没有文章，进行删除操作
        let resData = await query("delete from type where id = ?",[req.params.id])
        res.json({
            code:resData.affectedRows>0?0:400,
            msg:resData.affectedRows>0?'success':'error'
        })
    }
   
})

// 编辑类型
router.post("/editType/:id",async(req,res)=>{
    let data = await query("UPDATE `type` SET `name`=? WHERE (`id`=?)",[req.body.name,req.params.id]);

    res.json({
        code:data.affectedRows>0?0:400,
        msg:data.affectedRows>0?'success':'error'
    })
})

// 添加类型
router.post("/addType",async(req,res)=>{
    
    let data =await  query("INSERT INTO `type` (`name`) VALUES (?)",[req.body.name]);
    res.json({
        code:data.affectedRows>0?0:400,
        msg:data.affectedRows>0?'success':'error'
    })
})


router.get("/about",(req,res)=>{
    res.render("about")
})

router.get("/getAll",async(req,res)=>{
    let data = await query("select id,(SELECT username from user_table where id = article.user_id) as username , (SELECT `name` from type where id = article.type_id) as type_name,title,content,create_time  from article");
    res.json({
        code:0,
        data
    })
})



/**
 * 获取文章详情
 */
router.get("/detail/:id",async(req,res)=>{
    let data = await query("select * from article where id = ?",[req.params.id]);
    if(data[0]) data[0].create_time = timeFormat(data[0].create_time)
    res.render('detail',{data:data[0]});
})

/**
 * 获取某一类下的文章
 */
router.get("/type/:typeId",(req,res)=>{
    
})

/**
 * 获取某用户发布的文章
 */
router.get("/user/:userId",async(req,res)=>{
    let data = await query('select id,title from article where user_id = ?',[req.params.userId]);
    res.json({
        data
    })
})




/******************************以下功能需要验证是否停用用户************************************ */
router.get('/addArticle',async(req,res)=>{
    if(!req.session.user){
        res.redirect("/user/userLogin")
        return;
    }
    let data = await query("select * from type");
    res.render("write",{
        data
    });
})

/**
 * 写文章
 * 需要验证登录
 */
router.post("/add",async(req,res)=>{
    let data = await query("INSERT INTO `article` (`type_id`, `user_id`, `title`, `content`, `create_time`) VALUES (?,?,?,?,?)",[
        req.body.type_id,
        req.body.user_id,
        req.body.title,
        req.body.content,
        req.body.create_time
    ]);

    res.json({
        code:data.affectedRows>0?0:400,
        msg:data.affectedRows>0?'success':'error'
    })
})

/**
 * 修改文章
 * 需要验证登录
 */
router.put("/edit/:id",(req,res)=>{

})


/**
 * 获取公告
 */
router.get("/notice",async(req,res)=>{
    res.json({
        data:await query("select * from notice")
    })
})

/**
 * 删除文章
 * 需要验证登录
 */
router.post("/del/:id",async(req,res)=>{
    let data = await query("delete from article where id = ?",[req.params.id])
    res.json({
        code:data.affectedRows>0?0:400,
        msg:data.affectedRows>0?'success':'error'
    })
})

module.exports = router;




